// file转base64
// function filetoDataURL(file) {
//   var reader = new FileReader();
//   reader.readAsDataURL(file);
//   reader.onloadend = () => {
//     this.dataURLtoImage(reader.result)
//   };
// }

// bsae64转img
function dataURLtoImage(dataurl) {
  var img = new Image();
  img.src = dataurl;
  img.onload = () => {
    this.compress2(img)
  };
}

// base64转file
function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.dataURL.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {type: mime});
}

// 压缩
function compress2(img) {
  let w = img.width;
  let h = img.height;
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');
  canvas.setAttribute("width", w);
  canvas.setAttribute("height", h);
  ctx.drawImage(img, 0, 0, w, h);
  let quality = 0.6; // 压缩质量
  const base64 = canvas.toDataURL('image/jpeg', quality);
  this.dataurl = base64;
  this.srcList[0] = base64;
}

/**
 * 压缩图片
 * @param file 要压缩的图片
 * @param fn 回调函数 fn(压缩后的文件)
 */
export function compress(file, fn){
  var filename = file.name;
  var returnFile;
  var img = new Image();
  var reader = new FileReader();
  // file转dataurl
  reader.readAsDataURL(file);
  reader.onloadend = () => {
    // dataurl转img
    img.src = reader.result;
    img.onload = () => {
      // img转dataurl
      let w = img.width;
      let h = img.height;
      let canvas = document.createElement('canvas');
      let ctx = canvas.getContext('2d');
      canvas.setAttribute("width", w);
      canvas.setAttribute("height", h);
      ctx.drawImage(img, 0, 0, w, h);
      let quality = 0.5; // 压缩质量
      const base64 = canvas.toDataURL('image/jpeg', quality);
      // dataurl转file
      var arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      returnFile = new File([u8arr], filename, {type: mime});
      fn(returnFile);
    };
  };
}

/**
 * file转base64
 * @param file 要转换的图片
 * @param fn 回调函数fn(dataurl)
 */
export function fileToDateurl(file, fn){
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onloadend = () => {
    fn(reader.result);
  };
}
